/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author falxa
 */
public class DBConnector
{
    private String host;
    private String port;
    private String user;
    private String pwd;
    private String databasename;

    private Connection connection;
    
    public DBConnector(String host, String port, String user, String pwd, String databasename) 
    {
        this.host = host;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
        this.databasename = databasename;
    }

    public void connect()
    {
        try
        {
          Class.forName("com.mysql.jdbc.Driver");
          String url = "jdbc:mysql://"+this.host+":"+this.port+"/"+this.databasename;
          this.connection = DriverManager.getConnection(url,this.user, this.pwd);
        }
        catch(Exception e)
        {
            System.out.println("DB Connexion Error: "+e);
        }
    }
    
    public ResultSet executeQuery(String query)
    {
        Statement st;
        ResultSet rs = null;
        
        try
        {
            st = this.connection.createStatement();
            rs = st.executeQuery(query);
        }
        catch (SQLException ex)
        {
            System.out.println(ex+"\nUne erreur est survenue lors de l'exécution de la croquette :\n"+query);
        }
        
        return rs;
    }
    
    public boolean executeUpdate(String query)
    {
        boolean ok = false;
        Statement st;
        
        try
        {
            st = this.connection.createStatement();
            int rs = st.executeUpdate(query);
            ok = true;
            st.close();
        }
        catch (SQLException ex)
        {
            System.out.println(ex+"\nUne erreur est survenue lors de l'exécution de la croquette :\n"+query);
            ok = false;
        }
        
        return ok;
    } 

}
